package meiyunting.shiwuzhaoling_gatway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * 全局请求日志过滤器
 * 用于记录所有经过网关的请求信息
 */
@Slf4j
@Component
public class GlobalRequestLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        String method = request.getMethodValue();
        String path = uri.getPath();
        
        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        
        log.info("Gateway收到请求 - Method: {}, Path: {}, IP: {}", 
                method, path, request.getRemoteAddress().getHostString());
        
        // 记录请求头信息
        request.getHeaders().forEach((name, values) -> {
            if (name.equalsIgnoreCase("Authorization")) {
                log.debug("Header: {}, Value: {}", name, "******");
            } else {
                log.debug("Header: {}, Value: {}", name, formatHeaderValues(values));
            }
        });

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 计算请求处理时间
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            
            log.info("Gateway处理请求完成 - Method: {}, Path: {}, 耗时: {}ms, 状态码: {}", 
                    method, path, executionTime, exchange.getResponse().getStatusCode());
        }));
    }

    @Override
    public int getOrder() {
        // 确保此过滤器最先执行
        return Ordered.HIGHEST_PRECEDENCE;
    }
    
    /**
     * 格式化请求头值，避免日志过长
     */
    private String formatHeaderValues(List<String> values) {
        if (values == null || values.isEmpty()) {
            return "";
        }
        if (values.size() == 1) {
            return values.get(0);
        }
        return values.toString();
    }
} 